import _ from 'lodash';
import React from 'react';
import {Icon, Table} from 'antd';
import {toJS} from 'mobx';
import BaseView from '../base/View';
import MobileRow from './MobileRow';
import {Consumer} from '../../theme';
import utils from '../../../../../utils';
import {defaultHeight, heightKeys} from './data';
import './index.less';
import isMobile from '../../../../../utils/mobileDetect';
import { viewTypes } from "../../../../../constants/form";
import { WeaLocaleProvider } from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;

const { READONLY } = viewTypes;
const formatMultiLang = WeaLocaleProvider.formatMultiLang;

export default class DataTableView extends BaseView {
  containerRef = React.createRef();

  state = {
    widths: [],
    totalWidth: 0,
    selectedRowKeysAllPages: [],
    isShow: false,
    rowIndex: -1,
    suspension: 0,
    scrollTop: -1
  };

  componentDidMount() {
    utils.throttle.call(this, this.setMethodOfTable, 300, 5)();
  }

  setMethodOfTable() {
    if (!this.containerRef.current) return;
    const container = this.containerRef.current;
    const $table = container.querySelector('table tbody');

    if ($table) {
      const { suspension = 0 } = this.props.data;
      const checkbox = container.querySelector('.ant-table-selection-column');
      // 展示数据时会在左边增加一个border， 宽度需要-1
      const baseWidth = container.offsetWidth - (checkbox && checkbox.offsetWidth || 0) - 1; 
      const width = this.parseWidths(baseWidth);
      const flag = isMobile();

      if (flag && parseInt(suspension)) {
        $table.addEventListener('click', (event) => {
          const target = event.target;

          if (target.tagName == 'INPUT' && target.type == 'text') {
            let parentEle = target.parentNode;
            parentEle.click();
          }
        }, true);
      }

      this.setState({ ...width, suspension });
      return true;
    }
    return false;
  }

  componentWillUpdate(nextProps,nextState){
    const { isShow, scrollTop } = nextState;
    if(this.state.isShow === isShow) return;

    const $main = document.getElementById('container');
    if(isShow){
      $main.classList.add("mobile_hidden");
    }else{
      $main.classList.remove("mobile_hidden");
      if (scrollTop > 0) {
        utils.scrollSmoothTo(scrollTop);
      } 
    }
    return true;
  }

  parseWidths(baseWidth) {
    let newWidths = [];
    const minWidth = 160;
    const { widths } = this.props.data;

    newWidths = widths.map(w => Math.max(Math.round(w * baseWidth), minWidth));

    return {
      totalWidth: utils.reduce(newWidths),
      widths: newWidths.map(utils.toPixel)
    };
  }

  shouldRender() {
    const { data } = this.props;

    return data.coms.filter(Boolean).length;
  }

  onComValueChange(val, rowIndex, colIndex) {
    this.onValueChange(newValue => {
      newValue[rowIndex][colIndex] = val;
    });
  }

  addRow = (isContinue) => {
    const flag = isMobile();
    const suspension = this.state.suspension;
    let transitionTime = 0;

    if(flag && parseInt(suspension)){
      if (!isContinue) {
        const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
        this.setState({ scrollTop });
      }
      this.setState({ isShow: true, rowIndex: -1 });
      transitionTime = 350;
    }
    
    //mobile下保证添加页面加载完后再执行
    setTimeout(() => {
      const { defaultRowValue } = this.props.data;

      this.onValueChange(newValue => {
        const rowVals = toJS(defaultRowValue);
        const cloneVals = _.cloneDeep(rowVals);

        newValue.push(cloneVals);
      });
    } ,transitionTime);

  }

  onDel = () => {
    this.onValueChange(newValue => {
      _.remove(newValue, (v, i) => {
        return this.state.selectedRowKeysAllPages.includes(i)
      });
      this.setState({ selectedRowKeysAllPages: [] });
    });
  }

  onValueChange(handle) {
    const { value, onChange } = this.props;
    const newValue = toJS(value);

    handle(newValue);
    onChange(newValue);
  }

  renderExtra() {
    return (
      <span className='wea-edc-title-extra'>
        <span onClick={this.addRow}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@m0crq6`} type="plus" />{getLabel('506103','添加')}</span>
        <span className='delete' onClick={this.onDel}><Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@060q98`} type="minus" />{getLabel(502286, '删除')}</span>
      </span>
    )
  }

  getColumns() {
    const { widths } = this.state;
    const { coms } = this.props.data;

    return coms.filter(Boolean).map(({ config, uuid }, i) => ({
      title: (
        <Consumer ecId={`${this && this.props && this.props.ecId || ''}_Consumer@qefu7x@${uuid}`}>
          {({ field }) => (
            <div className='wea-edc-com-title f-ellipsis' title={formatMultiLang(config.title)} style={{ width: widths[i] }}>
              <label style={field.css}>
                <span className={config.required === '1' && 'wea-edc-com-required'}>
                  {formatMultiLang(config.title)}
                </span>
              </label>
              {!config.desc ? null : <label className='wea-edc-com-desc' dangerouslySetInnerHTML={{ __html: config.desc }} />}
            </div>
          )}
        </Consumer>
      ),
      dataIndex: uuid,
      key: uuid,
      width: widths[i]
    }));
  }

  getDatas() {
    const { data: { coms, errors }, renderItem, value } = this.props;
    const flag = isMobile();
    const suspension = this.state.suspension;

    return value.map((rowVals, rowIndex) => {
      const data = {};

      rowVals.forEach((value, colIndex) => {
        const com = coms[colIndex];
        if(!com)return;
        
        const uuid = com.uuid;
        let viewType = '';

        if (flag && parseInt(suspension)){
          viewType = READONLY
        }
        
        data[uuid] = renderItem(com, {
          key: `${uuid}_${rowIndex}_${colIndex}`,
          value,
          viewType,
          error: !errors[rowIndex] ? '' : errors[rowIndex][colIndex],
          onChange: value => this.onComValueChange(value, rowIndex, colIndex),
        });

        com.error = !errors[rowIndex] ? '' : errors[rowIndex][colIndex];

      });

      return data;
    });
  }

  onSelectedRowKeysChange = selectedRowKeysAllPages => {
    this.setState({ selectedRowKeysAllPages });
  }

  onChangeRow = isShow => {
    this.setState({isShow})
  }

  onRowClick = (event, rowKey) => {
    const flag = isMobile();
    const suspension = this.state.suspension;

    if(!(flag && parseInt(suspension))) return;

    const scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    this.setState({
      rowIndex:rowKey,
      isShow: true,
      scrollTop
    });
  }

  renderContent() {
    const { height = defaultHeight } = this.props.data;
    const { totalWidth, selectedRowKeysAllPages } = this.state;
    const scroll = { x: totalWidth };    

    if (heightKeys.Custom === height.key) {
      scroll.y = height.value;
    }

    return (
      <div ref={this.containerRef}>
        <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@83a39t`}
          onRowClick={this.onRowClick}
          locale={{
            emptyText: getLabel('511769','请点击添加，增加一条明细记录')
          }}
          columns={this.getColumns()}
          dataSource={this.getDatas()}
          rowSelection={{ 
            type: 'checkbox', 
            selectedRowKeysAllPages,
            onChange: this.onSelectedRowKeysChange 
          }}
          scroll={scroll}
          pagination={false}
        />
       <MobileRow ecId={`${this && this.props && this.props.ecId || ''}_MobileRow@bvcwzz`}
        isShow={this.state.isShow}
        rowIndex={this.state.rowIndex}
        onChangeRow={this.onChangeRow}
        onDel={this.onDel}
        addRow={this.addRow}
        parentProps={this.props}
       />
      </div>
    );
  }

  renderForReadonly() {
    const { height = defaultHeight } = this.props.data;
    const { totalWidth } = this.state;
    const scroll = { x: totalWidth };

    if (heightKeys.Custom === height.key) {
      scroll.y = height.value;
    }

    return (
      <div ref={this.containerRef}>
        <Table ecId={`${this && this.props && this.props.ecId || ''}_Table@0wnzcv`}
          locale={{
            emptyText: getLabel('511770','暂无明细记录')
          }}
          columns={this.getColumns()}
          dataSource={this.getDatas()}
          scroll={scroll}
          pagination={false}
        />
      </div>
    );
  }
  
}